﻿KISSY.add("fgt/ui/imgupload", function (S, Overlay) {
    function ImgUpload(config) {
        var self = this;

        self._init(config || {});
    }

    S.augment(ImgUpload, {
        _init: function (config) {
            var self = this,
                All = S.all;

            self.imgCDNServer = CONFIG["imgCDNServer"];
            self.config = S.merge(
            {
                containerID: "#img_uploader_popup",
                uploadifyID: "img_ufy_popup",
                defaultImgUrl: self.imgCDNServer + "static/img/menu_default.png"
            }, config);

            self.container = All(self.config.containerID);
            self.thumbnail = self.container.all(".thumbnail");
            self.imageTitle = self.container.all(".img-title");
            self.status = self.container.all(".status");
            self.uploadFn = self.container.all(".upload-fn");
            self.saveFn = self.container.all(".save-fn");
            self.saveBtn = self.container.all(".btn-save");
            self.cancelBtn = self.container.all(".btn-cancel");

            self.dialog = new Overlay.Dialog({
                prefixCls: "fgt-",
                srcNode: self.config.containerID,
                elStyle: {
                    position: S.UA.ie == 6 ? "absolute" : "fixed"
                },
                closable: true,
                align: {
                    points: ['cc', 'cc']
                },
                width: 396,
                mask: true,
                draggable: false,
                zIndex: 999999
            });
            self._statusRecover();
            self._bindEvent();

            self.isUploadInit = false;
        },

        _statusRecover: function () {
            var self = this;
            self.thumbnail.attr("src", self.config.defaultImgUrl);
            self.status.empty();
            self.uploadFn.show();
            self.saveFn.hide();
        },

        _uploaderInit: function () {
            var self = this,
                J = jQuery,
                uploadServer = CONFIG["uploadServer"],
                downLoadImageServer = CONFIG["downLoadImageServer"];

            J("#" + self.config.uploadifyID).uploadify({
                "uploader": "/static/flash/uploadify.swf",
                "script": uploadServer,
                "buttonImg": self.imgCDNServer + "static/img/upload/upload2.png",
                "width": 102,
                "height": 28,
                "scriptAccess": "always",
                "queueID": "uploader_queue",
                "queueSizeLimit": 1,
                "auto": true,
                "removeCompleted": false,
                "fileExt": "*.jpg;*.gif;*.png;*.jpeg",
                "scriptData": {
                    "usertype": "1",
                    "source": "/WebPortal/menu",
                    "_G_t": S.Cookie.get("_G_t"),
                    "_G_FA": S.Cookie.get("_G_FA"),
                    "_G_S": S.Cookie.get("_G_S")
                },
                "onSelect": function (event, id, fileObj) {
                    var imgUpload = self;
                    imgUpload.thumbnail.attr("src", imgUpload.config.defaultImgUrl);
                    imgUpload.status.html("<div class='progress'><div class='progress-bar'></div></div>");

                    return false;
                },
                "onCancel": function (event, id, fileObj, data) {
                    return false;
                },
                "onError": function (event, id, fileObj, errorObj) {
                    var imgUpload = self;
                    imgUpload.status.html("<p class='error'>上传失败</p>");

                    return false;
                },
                "onProgress": function (event, id, fileObj, data) {
                    var imgUpload = self,
                        progress = imgUpload.status.all(".progress"),
                        progressBar = progress.all(".progress-bar"),
                        ratio = data.percentage / 100;

                    if (progressBar[0]) {
                        S.Anim(progressBar[0],
                        {
                            'width': ratio * progress.width() + 'px'
                        }, 0.25);
                    }
                    return false;
                },
                "onComplete": function (event, id, fileObj, response, data) {
                    var imgUpload = self,
                        status = imgUpload.status,
                        result = S.JSON.parse(response),
                        resultCode = FGT.core.constant.jsonResultCode;

                    if (result.Result === resultCode.SUCCESS) {
                        var rc = result.Content,
                            imgSrc = downLoadImageServer + "/d/2/"+ rc.id + "(120x90).jpg";

                        self.imageStoreID = rc.id;
                        self.thumbnail.attr("src", imgSrc);
                        status.html("<p>上传成功！</p>");
                        imgUpload.uploadFn.hide();
                        imgUpload.saveFn.show();
                    }
                    else {
                        status.html("<p class='error'>上传失败</p>");
                    }
                    return false;
                }

            });

            self.isUploadInit = true;
        },

        _bindEvent: function () {
            var self = this,
                All = S.all;
            self.dialog.on("beforeVisibleChange", function (event) {
                if (event.newVal) {
                    self._statusRecover();
                }
                else {
                    All("#" + self.config.uploadifyID + "Uploader").css("visibility", "hidden");
                }
            });

            self.dialog.on("show", function (event) {
                if (!self.isUploadInit) {
                    self._uploaderInit();
                }
                All("#" + self.config.uploadifyID + "Uploader").css("visibility", "visible");
            });

            self.cancelBtn.on("click", function (event) {
                event.halt();
                self.dialog.hide();
            });

            self.saveBtn.on("click", function (event) {
                event.halt();
                var callback = self.config.saveCallback;
                if (callback) {
                    callback.call(self.config.context || self);
                }
            });
        },



        show: function (text, delay) {
            this.dialog.show();

        },

        hide: function () {
            this.dialog.hide();
        },

        setImageTitle: function (imageTitle) {
            this.imageTitle.text(imageTitle || "");
        },

        save: function (config) {
            var self = this,
                J = jQuery,
                paramStr = S.param(S.merge({ imageid: self.imageStoreID }, self.submitObj));

            J.ajax({
                url: config.url,
                type: "POST",
                data: paramStr,
                beforeSend: function (jqXHR, settings) {
                    self.saveBtn.prop("disabled", true);
                    self.status.html("<p>提交中...</p>");
                },
                success: function (data, textStatus, jqXHR) {
                    var resultCode = FGT.core.constant.jsonResultCode,
                        redirectUrl = self.redirectUrl;
                    if (data.Result === resultCode.SUCCESS) {
                        self.hide();
                        if (redirectUrl) {
                            window.location.href = redirectUrl;
                        }
                    }
                    else {
                        self.status.html("<p class='error'>提交失败，请稍候再试。</p>");
                    }
                    self.saveBtn.prop("disabled", false);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    self.status.html("<p class='error'>提交失败，请稍候再试。</p>");
                    self.saveBtn.prop("disabled", false);
                }
            });
        },

        setConfig: function (name, value) {
            this.config[name] = value;
        },
        setSaveData: function (submitObj) {
            this.submitObj = submitObj;
        },
        setRedirectUrl: function (redirectUrl) {
            this.redirectUrl = redirectUrl;
        }
    });

    return ImgUpload;
}, {
    requires: ["overlay"]
});